<template>
  <div class="index_box">
    <el-menu
      :default-active="activeIndex"
      v-model="activeIndex"
      style="position: fixed; z-index: 100"
      class="el-menu-demo
              right-align-menu
              with-shadow
              fixed-top"
      mode="horizontal">
      <el-menu-item index="1" @click="navigateTo('home')">
        <i class="el-icon-s-home"></i>主页
      </el-menu-item>
      <el-menu-item index="2" @click="navigateTo('news')">
        <i class="el-icon-s-promotion"></i> 最新动态
      </el-menu-item>
      <el-menu-item index="6" @click="navigateTo('notice')">
        <i class="el-icon-bell"></i> 系统通知
      </el-menu-item>
      <el-submenu index="3">
        <template slot="title"> <i class="el-icon-s-flag"></i>我的社团</template>
        <el-menu-item :index="'3-' + o.id" v-for="o in clubs" :key="o.id" @click="navigateTo('myclub/' + o.id)">
          {{o.name}}
        </el-menu-item>
      </el-submenu>
      <el-menu-item>
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            <el-avatar shape="circle"
                      :src="userInfo.avatar"></el-avatar>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="personal"> <i class="el-icon-user"></i> 个人中心</el-dropdown-item>
            <el-dropdown-item command="message"> <i class="el-icon-chat-dot-round"></i> 消息中心</el-dropdown-item>
            <el-dropdown-item command="logout"> <i class="el-icon-switch-button"></i> 退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-menu-item>
    </el-menu>
    <router-view/>
  </div>
</template>

<script>
import {getUserInfo} from "@/api/userAPI";
import httpInstance from "@/utils/http";

export default {
  data() {
    return {
      userInfo:{},
      clubs:[],
      activeIndex: this.getActiveIndex(), // 根据当前路由初始化激活状态
      departments: {}, // 用于存储学院数据
      user: localStorage.getItem("user"),
    }
  },

  methods: {
    // 获取社团列表   
    getClubList(){
      httpInstance({
        url: '/api/club',
        method: 'get'
      }).then(res => {
        console.log("社团列表",res)
        // 把 data中的id和title映射到clubs中
        this.clubs = res.data.map(item => ({
          id: item.id,
          name: item.title
        }))
      }).catch(err => {
        console.log(err)
      })
    },
    // 添加获取当前激活状态的方法
    getActiveIndex() {
      const route = this.$route.name;
      const routeToIndex = {
        'home': '1',
        'news': '2',
        'myclub': '3',
        'message': '4',
        'personal': '5',
        'notice': '6'
      };
      return routeToIndex[route] || '1';
    },

    navigateTo(path) {
      console.log(path);
      if (path.includes('myclub')) {
        const id = path.split('/')[1];
        this.$router.push({
          name: 'myclub',
          params: { id: id }
        });
      } else {
        this.$router.push({ name: path });
      }
    },

    // 退出登录
    logout() {
      httpInstance({
        url:'api/user/logout',
        method:'post'
      }).then(res => {
        if(res.code === 200){
          // 清除本地存储
          localStorage.removeItem("user")
          localStorage.removeItem("token")
          // 提示成功
          this.$message.success("退出成功")
          // 跳转到登录页
          this.$router.push('/login')
        } else {
          this.$message.error(res.message || "退出失败")
        }
      }).catch(err => {
        console.log(err)
        this.$message.error("退出失败")
        // 即使请求失败，也需要清除本地存储并跳转到登录页
        localStorage.removeItem("user")
        localStorage.removeItem("token")
        this.$router.push('/login')
      })
    },

    handleCommand(command) {
      if (command === 'logout') this.logout()
      else this.navigateTo(command)
    },

    init(){
      // 先从localStorage获取最新的用户信息
      const localUserInfo = JSON.parse(localStorage.getItem("user"));
      if (localUserInfo) {
        this.userInfo = localUserInfo;
      }
      
      // 再从服务器获取最新数据（可选）
      getUserInfo().then(res => {
        if (res.code === 200) {
          this.userInfo = res.data;
          localStorage.setItem("user", JSON.stringify(this.userInfo)); // 将用户信息保存到localStorage中
        }
      }).catch(err => {
        console.log("获取用户信息失败", err);
      });
    },

    // 获取学院列表
    getDepartments() {
      httpInstance({
        url: '/api/sys/dep',
        method: 'get'
      }).then(res => {
        if (res.code === 200) {
          this.departments = res.data;
        }
      }).catch(err => {
        console.log(err);
      });
    },

    goToActivityDetail(id) {
      this.$router.push({
        name: 'ActivityDetail',
        params: { id: id }
      })
    },

    // 处理用户信息更新事件
    handleUserInfoUpdated(updatedUser) {
      // 立即更新组件中的用户信息
      this.userInfo = {...updatedUser};
      localStorage.setItem("user", JSON.stringify(this.userInfo));
      // 强制组件刷新以显示新头像
      this.$forceUpdate();
    },
  },

  // 添加路由监听
  // 解释：当路由发生变化时，会触发这个监听器，然后会根据当前的路由来更新激活状态
  watch: {
    '$route': {
      immediate: true,
      handler(to) {
        const routeToIndex = {
          'home': '1',
          'news': '2',
          'myclub': '3',
          'message': '4',
          'personal': '5',
          'notice': '6'
        };
        this.activeIndex = routeToIndex[to.name] || '1';
      }
    }
  },

  // 组件创建时设置激活状态
  created() {
    this.activeIndex = this.getActiveIndex();
    this.init();
    this.getDepartments();
    
    // 监听用户信息更新事件
    this.$bus.$on('userInfoUpdated', this.handleUserInfoUpdated);
  },

  // 组件挂载时获取社团列表/学院列表
  mounted() {
    this.getClubList(); // 获取社团列表
    this.getDepartments(); // 获取学院列表
  },
  
  beforeDestroy() {
  // this.logout() // 关闭页面前退出登录
    // 移除事件监听器
    this.$bus.$off('userInfoUpdated', this.handleUserInfoUpdated);
  }
}
</script>

<style>

.right-align-menu {
  justify-content: flex-end;
  display: flex;
}

.with-shadow {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果，水平偏移0，垂直偏移2px，模糊半径4px，阴影颜色为rgba(0, 0, 0, 0.1) */
}

.fixed-top {
  margin-bottom: 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100; /* 确保导航栏在其他元素之上 */
}
</style>

